package io.renren.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import com.alibaba.fastjson.JSONArray;

import org.springframework.stereotype.Controller;

import io.renren.entity.DictDepartmentEntity;
import io.renren.entity.xtd.DictDepartmentEntityXtd;
import io.renren.service.DictDepartmentService;
import io.renren.service.SysWorkLogService;
import io.renren.service.xtd.DataContractpayServiceXtd;
import io.renren.service.xtd.DictDepartmentServiceXtd;
import io.renren.service.xtd.DictEmployeeServiceXtd;
import io.renren.service.xtd.HisDepartmentServiceXtd;
import io.renren.utils.AssignUtils;
import io.renren.utils.Common;
import io.renren.utils.ExcelUtils;
import io.renren.utils.PageUtils;
import io.renren.utils.R;
import io.renren.utils.ShiroUtils;


/**
 * 部门表
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-05-20 14:55:35
 */
@Controller
@RequestMapping("dictdepartment")
public class DictDepartmentController {
	@Autowired
	private DictEmployeeServiceXtd dictEmployeeServiceXtd;
    @Autowired
	private SysWorkLogService sysWorkLogService;
	@Autowired
	private DataContractpayServiceXtd dataContractpayServiceXtd;
	@Autowired
	private HisDepartmentServiceXtd hisDepartmentServiceXtd;
	@Autowired
	private DictDepartmentService dictDepartmentService;
	@Autowired
	private DictDepartmentServiceXtd dictDepartmentServiceXtd;
	@RequestMapping("/dictdepartment.html")
	public String list(){
		return "dictdepartment/dictdepartment.html";
	}
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	@RequiresPermissions("dictdepartment:list")
	public R list(Integer page, Integer limit){
		Map<String, Object> map = new HashMap<>();
		map.put("offset", (page - 1) * limit);
		map.put("limit", limit);
		
		//查询列表数据
		List<DictDepartmentEntity> dictDepartmentList = dictDepartmentService.queryList(map);
		int total = dictDepartmentService.queryTotal(map);
		
		PageUtils pageUtil = new PageUtils(dictDepartmentList, total, limit, page);
		
		return R.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 树形列表
	 */
	@ResponseBody
	@RequestMapping("/treelist")
	public R treelist(String name, String sort, String order) {
		Map<String, Object> map = new HashMap<>();
		String username = null;
		if (name != null) {
			username = name.trim();
		}
		map.put("name", username);
		map.put("orderby", " order by orderNo asc ");
//		if (sort.isEmpty() || sort == null) {
//
//		} else {
//			//map.put("orderby", " order by " + sort + " " + order + " ");
//		}
		// 查询列表数据
		List<DictDepartmentEntity> dictDepartmentList = dictDepartmentService.queryList(map);

		return R.ok().put("list", dictDepartmentList);
	}
	
	/**
	 * 信息
	 */
	@ResponseBody
	@RequestMapping("/info/{id}")
	@RequiresPermissions("dictdepartment:info")
	public R info(@PathVariable("id") String id){
		DictDepartmentEntity dictDepartment = dictDepartmentService.queryObject(id);
		
		return R.ok().put("dictDepartment", dictDepartment);
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping("/save")
	@RequiresPermissions("dictdepartment:save")
	public R save(@RequestBody DictDepartmentEntity dictDepartment){
		dictDepartmentService.save(dictDepartment);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("dictdepartment:update")
	public R update(String json) {
		Map<String, Object> map = new HashMap<>();
		json=json.substring(1, json.length()-1);
		if(json!=null){
			Map<String,Object> parmmap=(Map<String,Object>) JSONArray.parse(json);
			/*String str = (String) parmmap.get("name");
		    String regEx = "^[\u0391-\uFFE5]{1,10}$";
		    Pattern pattern = Pattern.compile(regEx);
		    Matcher matcher = pattern.matcher(str);
		    boolean rs = matcher.find();
		    if (StringUtils.isBlank((String) parmmap.get("name"))) {
				return R.error("名称不能为空");
			}
			if (rs==false) {
				return R.error("必须1~10个全汉字");
			}*/
			if(parmmap.get("addFlag")==null){
			   map.put("id", parmmap.get("id").toString());
			   map.put("name", parmmap.get("name"));
			   /*int total = dictDepartmentService.queryTotal(map);
				if (total!=0){
					return R.error("名称已存在");
				}*/
				dictDepartmentServiceXtd.updateXtd(map);
			}else{
				map.put("name", parmmap.get("name"));
				map.put("fid", parmmap.get("fid"));
				map.put("state", true);
				int total = dictDepartmentService.queryTotal(map);
				/*if (total!=0){
					return R.error("名称已存在");
				}*/
				dictDepartmentServiceXtd.saveXtd(map);
			}
		}
		

		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	@RequiresPermissions("dictdepartment:delete")
	public R delete(@RequestBody String id){
		//dictDepartmentService.deleteBatch(ids);
		
		return R.ok();
	}
	
	/**
	 * 选择部门树
	 */
	@ResponseBody
	@RequestMapping("/orderlist")
	@RequiresPermissions("dictdepartment:list")
	public R orderlist(){
		//查询列表数据
		List<DictDepartmentEntityXtd> queryOrderList = (List<DictDepartmentEntityXtd>) dictDepartmentServiceXtd.queryOrderList();
		
		//添加顶级菜单
		/*DictDepartmentEntityXtd root = new DictDepartmentEntityXtd();*/
		/*root.setMenuId(0L);
		root.setName("一级菜单");
		root.setParentId(-1L);
		root.setOpen(true);
		menuList.add(root);*/
		
		return R.ok().put("deptList", queryOrderList);
	}
	/**
	 * 查询是否存在历史部门
	 */
	@ResponseBody
	@RequestMapping("/hashis")
	public R hasHisDept(HttpServletRequest request){
		Map<String,String> time = new HashMap<String,String>();
		String date = request.getParameter("time");
		time.put("year", date.substring(0,4));
		time.put("month", date.substring(5,7));
		if(dictDepartmentServiceXtd.hasHis(time) == 0){
			return R.error();
		}
		
		return R.ok();
	}
	/**
	 * 存为历史部门
	 */
	@ResponseBody
	@RequestMapping("/tohis")
	public R toHisDept(HttpServletRequest request){
		Map<String,String> time = new HashMap<String,String>();
		String date = request.getParameter("time");
		time.put("year", date.substring(0,4));
		time.put("month", date.substring(5,7));
		if(dictDepartmentServiceXtd.toHis(time)!=0){
/*			dictDepartmentServiceXtd.emptyDept();*/
		}
			
		return R.ok();
	}
	/**
	 * 导入excel
	 */
	@ResponseBody
	@RequestMapping("/upload")
	public R upload(@RequestParam("file") MultipartFile multfile,String time) throws Exception {
		try {
			if(time==null || time.length()==0 || time.indexOf("-")<0){
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "组织架构导入失败",
	        			"未选择数据时间", "");
				return R.error("请选择数据时间");
			}
			R resultR = ExcelUtils.textDepExcel(multfile.getInputStream(),0);
			if (Integer.parseInt(resultR.get("code").toString())!=0) {
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "组织架构导入失败",
	        			resultR.get("msg").toString(), time);
				return resultR;
				
			}
			Integer showType=0;
			Map<String, Object> map=new HashMap<>();
			map.put("year", Integer.parseInt(time.split("-")[0]));
			map.put("month", Integer.parseInt(time.split("-")[1]));
			int total = hisDepartmentServiceXtd.queryTotalXtd(map);
			if (total>0) {
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "组织架构导入失败",
	        			"已有历史数据，不可再导入", time);
				return R.error("已有历史数据，不可再导入");
			} else {
				if(Integer.valueOf(map.get("month").toString())==1){
					map.remove("year");
					map.put("year", Integer.parseInt(time.split("-")[0])-1);
					map.remove("month");
					map.put("month", 12);
				}else{
					map.remove("month");
					map.put("month", Integer.parseInt(time.split("-")[1])-1);
				}
				total = hisDepartmentServiceXtd.queryTotalXtd(map);
				Map<String, Object> hismap=new HashMap<>();
				int histotal = hisDepartmentServiceXtd.queryTotalXtd(hismap);
				if(total==0 && histotal!=0){
					Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
		        			ShiroUtils.getUserEntity().getUsername(), "组织架构导入失败",
		        			"请先将上个月组织架构转存历史，再导入", time);
					return R.error("请先将上个月组织架构转存历史，再导入");
				}
				Map<String, Object> mapb=new HashMap<>();
				mapb.put("year", time.split("-")[0]);
				mapb.put("month", time.split("-")[1]);
				total = dataContractpayServiceXtd.queryTotalXtd(mapb);
				if(total==0){
					showType=0;
				}else{
					showType=1;
				}
			}
			Map<String, Object> mapc = new HashMap<>();
			mapc.put("orderby", " order by orderNo asc ");
			List<DictDepartmentEntity> dictDepartmentList = dictDepartmentService.queryList(mapc);
			List<List<Object>> list = ExcelUtils.readExcel(multfile.getInputStream(),0);
			List<Map<String, Object>> dept = AssignUtils.assignToDeptNewUuid(list);
			if (dictDepartmentList==null || dictDepartmentList.size()==0) {
				
				dictDepartmentServiceXtd.impExcelInList(dept);
				Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
	        			ShiroUtils.getUserEntity().getUsername(), "组织架构导入成功",
	        			"", time);
				return R.ok();	
			}else{
				
				if (dept==null || dept.size()==0) {
					dictDepartmentServiceXtd.impExcelInList(dept);
					Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
		        			ShiroUtils.getUserEntity().getUsername(), "组织架构导入成功",
		        			"", time);
					return R.ok();	
				} else {
                    for(int n=0;n<dept.size();n++){
                    	Map<String, Object> mapd = dept.get(n);
                    	for(int m=0;m<dictDepartmentList.size();m++){
                    		if(dictDepartmentList.get(m).getDeptNo().equals(mapd.get("deptno"))){
                    			dept.get(n).remove("id");
                    			dept.get(n).put("id", dictDepartmentList.get(m).getId());
                    			break;
                    		}
                    	}
                    }
                    dictDepartmentServiceXtd.deleteAll();
                    dictDepartmentServiceXtd.impExcelInList(dept);
                    Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
		        			ShiroUtils.getUserEntity().getUsername(), "组织架构导入成功",
		        			"", time);
					return R.ok();	
				}
			}
			
		} catch (Exception e) {
			Common.createWorkLog(dictEmployeeServiceXtd, sysWorkLogService,
        			ShiroUtils.getUserEntity().getUsername(), "组织架构导入失败",
        			"导入失败", time);
			return R.error("导入失败");
		}
		
	}
}
